<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ page import="java.util.*" %>
<%@ page import="java.nio.charset.StandardCharsets" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.ByteArrayInputStream" %>
 <%@ page import="org.json.simple.JSONObject" %>
 <%@ page import="org.json.simple.parser.JSONParser" %>
 <%@ page import="org.json.simple.JSONArray" %>
 <%@ page import="com.netcracker.studportal.server.facade.*" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Admin View - Assign Exam</title>
<link href="style/css/addStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="header">
    <div class="wrapper">
        	<a href = "<% out.print("indexAdmin.jsp"); %>" >
        	<div class="logo">
        	<div class="exit"><a href = "<% out.print("logout.jsp"); %>" ><img src="style/img/exit.jpg"></a> </div> 
             <a href = "<% out.print("indexAdmin.jsp"); %>" ><img src="style/img/logo.png" class="log"></a>
            </a>
    </div>
</div>
    <div class="content">
    	<div class="wrapper">
        	<div class="left">
            	<ul class="top-menu">
                    <li><a href="<% out.print("admin.jsp?action=addStudent"); %>">Добавить нового студента</a></li>
                    <li><a href="<% out.print("admin.jsp?action=addProfessor"); %>">Добавить преподавателя</a></li>
                    <li><a href="<% out.print("admin.jsp?action=addExam"); %>">Добавить экзамен</a></li>
                    <li><a href="<% out.print("admin.jsp?action=AssignExam"); %>">Назначить экзамен</a></li>
       
            	</ul>
            </div>
            <div class="right">
            	<div class="input_data">



<form method="post" action="AssignExam.jsp">
 
<select name="univ_id" style="width: 149px; ">
	<option value=""></option>
<%
	String resultMessage = null;

	JSONParser parser = new JSONParser();	
	FacadeAdmin adminFacade = new FacadeAdmin();
	
	String universities = adminFacade.getAllUniversity();
	
	Object resUniv = parser.parse(universities);
	if (resUniv instanceof JSONArray) {
		JSONArray jsonArray = (JSONArray) resUniv;
		Iterator<JSONObject> i = jsonArray.iterator();
						
		while(i.hasNext()) {
	    	JSONObject data = i.next();
	    	String universityID = data.get("univ_id").toString();
	    	String universityName = data.get("univ_name").toString();
	      
	    	String selectedUnivID = request.getParameter("univ_id");
	    	if (selectedUnivID != null && selectedUnivID.equals(universityID)) {
	    		out.println("<option selected = \"selected\" value=\""+universityID+"\">"+universityName+"</option>"); 
	    	} else {
	    		out.println("<option value=\""+universityID+"\">"+universityName+"</option>"); 
	    	}
	 	}
	} else {
		JSONObject jsonObj = (JSONObject) resUniv;
		String error = jsonObj.get("error").toString();
		out.print("Упс, ошибочка вышла: " + error);
	}
%>
</select> Университет <br>
 <% if (request.getParameter("univ_id") != null) { %>
 <select name="prof_id" style="width: 149px; ">
	<option value=""></option>
<%
	String univ_id = request.getParameter("univ_id").toString();
	JSONObject inputParams = new JSONObject();
	inputParams.put("univ_id",univ_id);

	String professors = adminFacade.getProfsByUniversity(inputParams.toJSONString());

	Object resultObj = parser.parse(professors);
	if (resultObj instanceof JSONArray) {
		JSONArray jsonArray = (JSONArray) resultObj;
		Iterator<JSONObject> i = jsonArray.iterator();
					
		while(i.hasNext()) {
			JSONObject data = i.next();
			String id = data.get("prof_id").toString();
			String name = data.get("last_name").toString() + " " +
					data.get("first_name").toString() + " " +
					data.get("patronymic").toString();
					
			String selectedProfID = request.getParameter("prof_id");
      		if (selectedProfID != null && selectedProfID.equals(id)) {
       			out.println("<option selected = \"selected\" value=\""+id+"\">"+name+"</option>"); 
      		} else {
       			out.println("<option value=\""+id+"\">"+name+"</option>"); 
      		}
		}
	} else {
		JSONObject jsonObj = (JSONObject) resultObj;
		String error = jsonObj.get("error").toString();
		out.print("Упс, ошибочка вышла: " + error);
	}
%>
</select> Преподаватель <br>
<% } 
if (request.getParameter("prof_id") != null) { %>

<select name="exam_id" style="width: 149px; ">
	<option value=""></option>
<%
	String prof_id = request.getParameter("prof_id").toString();
	JSONObject inputParams = new JSONObject();
	inputParams.put("prof_id",prof_id);

	String exams = adminFacade.getExamsByProfessor(inputParams.toString());

	Object resultObj = parser.parse(exams);
	if (resultObj instanceof JSONArray) {
		JSONArray jsonArray = (JSONArray) resultObj;
		Iterator<JSONObject> i = jsonArray.iterator();
		while(i.hasNext()) {
			JSONObject data = i.next();
			String id = data.get("exam_id").toString();
			String name = data.get("subject_name").toString();
			String examDate = data.get("exam_date").toString();
			String displayedName = name+" - "+examDate;

			String selectedExamID = request.getParameter("exam_id");
	      	if (selectedExamID != null && selectedExamID.equals(id)) {
	       		out.println("<option selected = \"selected\" value=\""+id+"\">"+displayedName+"</option>"); 
	      	} else {
	       		out.println("<option value=\""+id+"\">"+displayedName+"</option>"); 
	      	}
		}
	} else {
		JSONObject jsonObj = (JSONObject) resultObj;
		String error = jsonObj.get("error").toString();
		out.print("Упс, ошибочка вышла: " + error);
	}				
%>
</select> Экзамен <br>
<% } 
if (request.getParameter("exam_id") != null) { %>

<select name="faculty_id" style="width: 149px; ">
	<option value=""></option>
<%
	String univ_id = request.getParameter("univ_id").toString();
	JSONObject inputParams=new JSONObject();
	inputParams.put("univ_id",univ_id);

	String faculties = adminFacade.getFacultiesByUniversity(inputParams.toString());
					
	Object resultObj = parser.parse(faculties);
	if (resultObj instanceof JSONArray) {
		JSONArray jsonArray = (JSONArray) resultObj;
		Iterator<JSONObject> i = jsonArray.iterator();
		while(i.hasNext()) {
			JSONObject data = i.next();
			String id = data.get("faculty_id").toString();
			String name = data.get("faculty_name").toString();
			
			String selectedFacID = request.getParameter("faculty_id");
			if (selectedFacID != null && selectedFacID.equals(id)) {
				out.println("<option selected = \"selected\" value=\""+id+"\">"+name+"</option>"); 
			} else {
				out.println("<option value=\""+id+"\">"+name+"</option>"); 
			}
		}
	} else {
		JSONObject jsonObj = (JSONObject) resultObj;
		String error = jsonObj.get("error").toString();
		out.print("Упс, ошибочка вышла: " + error);
	}
%>
</select> Факультет <br>

<% } 
if (request.getParameter("faculty_id") != null) { %>

<select name="course_and_group" style="width: 149px; ">
	<option value=""></option>
<%
	String faculty_id = request.getParameter("faculty_id").toString();
	JSONObject inputParams = new JSONObject();
	inputParams.put("faculty_id", faculty_id);

	String groups = adminFacade.getGroupsByFaculty(inputParams.toString());
	Object resultObj = parser.parse(groups);
	if (resultObj instanceof JSONArray) {
		JSONArray jsonArray = (JSONArray) resultObj;
		Iterator<JSONObject> i = jsonArray.iterator();
		while(i.hasNext()) {
			JSONObject data = i.next();
			String group = data.get("group_num").toString();
			String course = data.get("course").toString();
			String displayedName = course + " курс - " + group + " группа";
			String value = course + ":" + group;
			
			String selectedCourseAndGroup = request.getParameter("course_and_group");
      		if (selectedCourseAndGroup != null && selectedCourseAndGroup.equals(value)) {
       			out.println("<option selected = \"selected\" value=\""+value+"\">"+displayedName+"</option>"); 
      		} else {
       			out.println("<option value=\""+value+"\">"+displayedName+"</option>"); 
      		}
		}
	} else {
		JSONObject jsonObj = (JSONObject) resultObj;
		String error = jsonObj.get("error").toString();
		out.print("Упс, ошибочка вышла: " + error);
	}
%>
</select> Группа <br>
<%}

if (request.getParameter("exam_id") != null &&
	request.getParameter("faculty_id") != null &&
	request.getParameter("course_and_group") != null) {

	request.setCharacterEncoding("UTF-8");
	String exam_id = request.getParameter("exam_id");
	String faculty_id = request.getParameter("faculty_id");
	String courseAndGroup = request.getParameter("course_and_group");
	String course = courseAndGroup.split(":")[0];
	String group = courseAndGroup.split(":")[1];
	
	JSONObject inputParams = new JSONObject();
	inputParams.put("exam_id",exam_id);
	inputParams.put("faculty_id",faculty_id);
	inputParams.put("course",course);
	inputParams.put("group_num",group);
		
	String result = adminFacade.addExamToStudentsGroup(inputParams.toString());
	JSONObject jsonObj = (JSONObject) parser.parse(result);
	if ("success".equals(jsonObj.get("status"))) {
		resultMessage = "<font color=green>Экзамен успешно назначен!</font>";
	} else {
		resultMessage = "<font color=red>При выполнении запроса возникли ошибки.</font>";
	}
}
%>
<input type="submit" value="ОК"><br />
<%
  if (resultMessage != null) {
	  out.print("Результат: " + resultMessage);
  }
%>
</form>
</div>
</div>
<div class="clear"></div>
 </div>
    </div>
    <div class="footer">
    	<div class="wrapper">
        	<div class="copy">
            	<p>Студенческий портал. 2014 &copy; by NetCracker</p>
            </div>
        </div>
    </div>	



</body>
</html>